import React from 'react'

import CommentSend from '../CommentSend'
import CommentList from '../CommentList'

import CommentContext from '../commentConext'

class Comments extends React.Component {
  state = {
    comments: [
      {
        id: 1,
        name: 'jser',
        comment: '一听就懂！👍',
        like: 98,
        isLike: false,
        isHate: false,
        createTime: new Date('2021-01-30 21:39:35')
      },
      {
        id: 2,
        name: 'jser',
        comment: '一听就懂！👍',
        like: 0,
        isLike: false,
        isHate: false,
        createTime: new Date('2021-01-30 21:39:35')
      }
    ]
  }

  onSend = comment => {
    const { comments } = this.state

    const id = comments.length === 0 ? 1 : comments[comments.length - 1].id + 1
    const newComments = [
      ...this.state.comments,
      {
        id,
        name: 'jser',
        comment,
        like: 0,
        isLike: false,
        isHate: false,
        createTime: new Date()
      }
    ]

    this.setState({ comments: newComments })
  }

  onLikeHate = (id, type) => {
    const newComments = this.state.comments.map(item => {
      if (id === item.id) {
        let isLike = item.isLike,
          like = item.like,
          isHate = item.isHate

        if (type === 'like') {
          isLike = !item.isLike
          isHate = item.isHate ? false : item.isHate
          like = isLike ? item.like + 1 : item.like - 1
        } else {
          isHate = !item.isHate
          isLike = item.isLike ? false : item.isLike
          like = item.isLike ? item.like - 1 : item.like
        }

        return {
          ...item,
          isHate,
          isLike,
          like
        }
      }

      return item
    })
    this.setState({ comments: newComments })
  }

  render() {
    const { comments } = this.state

    return (
      <div className="comment-container">
        {/* 评论数 */}
        <div className="comment-head">
          <span>{comments.length} 评论</span>
        </div>
        {/* 排序 */}
        <div className="tabs-order">
          <ul className="sort-container">
            <li data-sort="1" className="on">
              按热度排序
            </li>
            <li data-sort="2">按时间排序</li>
          </ul>
        </div>
        {/* 发表评论 */}
        <CommentSend onSend={this.onSend} />

        <CommentContext.Provider
          value={{
            dispatch: this.onLikeHate
          }}
        >
          {/* 列表 */}
          <CommentList comments={comments} />
        </CommentContext.Provider>
      </div>
    )
  }
}

export default Comments
